package Arrays;

public class _289_GameofLife {
    int[][] board;
    public void gameOfLife(int[][] board) {
        this.board = board;
        int[][] res = new int[board.length][board[0].length];
        for (int i = 0; i < res.length; i++) {
            for (int j = 0; j < res[0].length; j++) {
                res[i][j] = populate(i, j);
            }
        }
        for (int i = 0; i < res.length; i++) {
            board[i] = res[i].clone();
        }
    }

    public int populate(int row, int column) {
        int count = 0;
        if (row - 1 > -1) {
            count += board[row - 1][column];
            if (column - 1 > -1) {
                count += board[row - 1][column - 1];
            }
            if (column + 1 < board[0].length) {
                count += board[row - 1][column + 1];
            }
        }
        //middle level
        if (column - 1 > -1) {
            count += board[row][column - 1];
            if (row + 1 < board.length) {
                count += board[row + 1][column - 1];
            }
        }
        if (column + 1 < board[0].length) {
            count += board[row][column + 1];
            if (row + 1 < board.length) {
                count += board[row + 1][column + 1];
            }
        }
        if (row + 1 < board.length) {
            count += board[row + 1][column];
        }
        if ((board[row][column] == 0 && count == 3) || (board[row][column] == 1 && (count == 2 || count == 3))) {
            return 1;
        } else {
            return 0;
        }
    }
}
